package com.example.demo6.ui.regist;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import com.example.demo6.MyUserHelper;
import com.example.demo6.R; // 替换为你的包名
import com.example.demo6.SQLite.MyDatabase;
import com.example.demo6.SQLite.User;

public class registFragment extends Fragment {

    private EditText editUsername, editUserId, editUserPassword, editUserPhone, editUserRegion;
    private Button registBtn, exitBtn;
    private TextView toLogin;
    private MyUserHelper dbHelper;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_regist, container, false);

        // 初始化视图
        initViews(view);

        // 初始化数据库帮助类
//        dbHelper = new MyUserHelper(getActivity());

        // 注册按钮点击事件
        registBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = editUsername.getText().toString().trim();
                String userIdStr = editUserId.getText().toString().trim();
                String password = editUserPassword.getText().toString().trim();
                String phone = editUserPhone.getText().toString().trim();
                String region = editUserRegion.getText().toString().trim();

                if (username.isEmpty() || userIdStr.isEmpty() || password.isEmpty() || phone.isEmpty() || region.isEmpty()) {
                    Toast.makeText(getActivity(), "所有字段均为必填项", Toast.LENGTH_SHORT).show();
                    return;
                }

                try {
                    int userId = Integer.parseInt(userIdStr.trim()); // 确保去除前后空格后转换
                    long phoneNumber = Long.parseLong(phone.trim()); // 同样处理电话号码
                    User newUser = new User(userId, username, password, phoneNumber, region);
                    new registerTask(userId, username, password, phoneNumber, region).execute();

                } catch (NumberFormatException e) {
                    // 分析异常信息以提供更具体的反馈
                    String errorMessage;
                    if (e.getMessage().contains("userIdStr")) {
                        errorMessage = "用户ID包含非数字字符，请检查后重新输入";
                    } else if (e.getMessage().contains("phone")) {
                        errorMessage = "电话号码必须是有效数字";
                    } else {
                        errorMessage = "输入的数字格式有误，请检查";
                    }
                    Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT).show();
                    Log.e("RegistrationError", "Conversion error: " + errorMessage, e);
                }
            }
        });

        // 其他按钮事件可以在这里处理，如退出或去登录的逻辑

        return view;
    }

    public class registerTask extends AsyncTask<Void,Void,Void>{
        int userId;
        Long phoneNumber;
        String username,password,region;
        User user;

        public registerTask(int userId,  String username, String password,Long phoneNumber, String region) {
            this.userId = userId;
            this.phoneNumber = phoneNumber;
            this.username = username;
            this.password = password;
            this.region = region;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            user=MyDatabase.getInstance(getActivity()).userDao().getUserByUserId(userId);
            if (user==null){
                MyDatabase.getInstance(getActivity()).userDao().insertUserByUser(userId, username, password, phoneNumber, region);
            }
            return null;
        }
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            if (user == null) {
                Toast.makeText(getActivity(), "注册成功", Toast.LENGTH_SHORT).show();
                NavController navController = Navigation.findNavController(getActivity(), R.id.nav_host_fragment_activity_main);
                navController.navigate(R.id.loginFragment);
            } else {
                Toast.makeText(getActivity(), "注册失败，请重试", Toast.LENGTH_SHORT).show();
                Log.e("RegistrationError", "Insertion failed with no specific error code");
            }
        }

        // 清空输入框的方法
        private void clearInputFields() {
            editUsername.setText("");
            editUserId.setText("");
            editUserPassword.setText("");
            editUserPhone.setText("");
            editUserRegion.setText("");
        }
    }

    private void initViews(View view) {
        editUsername = view.findViewById(R.id.editusername);
        editUserId = view.findViewById(R.id.edituserid);
        editUserPassword = view.findViewById(R.id.edituserpassword);
        editUserPhone = view.findViewById(R.id.edituserphone);
        editUserRegion = view.findViewById(R.id.edituserregion);
        registBtn = view.findViewById(R.id.registbtn);
        exitBtn = view.findViewById(R.id.exitbtn1);
        toLogin = view.findViewById(R.id.tologin);
    }
}